package com.hb.util;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class CompressUtils {
    public static byte[] compress(byte[] data) {
        GZIPOutputStream gzip = null;
        ByteArrayOutputStream outData = null;
        try {
            outData = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(outData);
            gzip.write(data);
            gzip.close();
            return outData.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(gzip);
            IOUtils.closeQuietly(outData);
        }
        return null;
    }

    public static byte[] uncompress(byte[] data) {
        InputStream in = null;
        GZIPInputStream gzip = null;
        try {
            in = new ByteArrayInputStream(data);
            gzip = new GZIPInputStream(in);
            byte[] bs = IOUtils.toByteArray(gzip);
            return bs;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(gzip);
        }
        return null;
    }
}
